package com.ysu.zyw.common.util;

import java.io.*;

import com.ysu.zyw.common.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * SerializerUtil provide an set of operation for serialization.
 * <p>
 * Created by ZeRur on 2016/1/17.
 *
 * @author yaowu.zhang
 */
public class SerializerUtil {

    private static final Logger logger = LoggerFactory.getLogger(SerializerUtil.class);

    /**
     * serialize an object to byte array, jdk mode.
     *
     * @param value object
     * @return byte
     */
    public static byte[] serialize(Serializable value) {
        Assert.notNull(value, "null text is not allowed");
        byte[] bytes;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(value);
            bytes = byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            logger.error("SerializerUtil - serialize - ", e);
            throw new SystemException(e);
        }
        return bytes;
    }

    /**
     * deserialize an byte array to an object, jdk mode.
     *
     * @param bytes byte array
     * @param clazz type byte array to be convert to
     * @param <T>   type byte array to be convert to
     * @return object
     */
    @SuppressWarnings("unchecked")
    public static <T> T deserialize(byte[] bytes, Class<T> clazz) {
        Assert.notNull(bytes, "null bytes is not allowed");
        Assert.notNull(clazz, "null clazz is not allowed");
        Object object;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            object = objectInputStream.readObject();
        } catch (Exception e) {
            logger.error("SerializerUtil - deserialize - ", e);
            throw new SystemException(e);
        }
        return clazz.cast(object);
    }

    /**
     * serialize an str
     *
     * @param text str to be serialized
     * @return bytes
     */
    public static byte[] serializeStr(String text) {
        Assert.hasText(text, "empty text is not allowed");
        return text.getBytes();
    }

    /**
     * deserialize bytes to an str
     *
     * @param bytes bytes
     * @return str
     */
    public static String deserializeStr(byte[] bytes) {
        Assert.notNull(bytes, "null bytes is not allowed");
        return new String(bytes);
    }

}
